﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SRF.Data
{
    public class DBHelperFactory
    {
        static IDictionary<string,DBHelperBase> dbhelperList;
        static object lockObject;

        static DBHelperFactory()
        {
            dbhelperList = new Dictionary<string, DBHelperBase>();
            lockObject = new object();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static DBHelperBase GetDBHelper(string name = "")
        {
            DBHelperBase dbhelper;
            lock (lockObject)
            {
                if (string.IsNullOrEmpty(name) && dbhelperList.Count() > 0)
                {
                    dbhelper = dbhelperList.Values.First();
                }
                else
                {
                    name = name.ToLower();
                    if (!dbhelperList.TryGetValue(name, out dbhelper))
                    {
                        var config = new Cfg.Configuration().Configure(ConfigFile);
                        Cfg.ConnectionInfo ci;
                        if (config.Connections.TryGetValue(name, out ci))
                        {
                            dbhelper = new DBHelper(ci.DbType, ci.ConnectionString);
                            dbhelper.ClassMappings = config.ClassMappings;
                            dbhelper.Queries = config.Queries;
                            dbhelperList.Add(name, dbhelper);
                        }
                    }
                }
            }

            return dbhelper;
        }

        static string _configFile;
        /// <summary>
        ///  配置文件 
        /// </summary>
        public static string ConfigFile
        {
            get
            {
                if (string.IsNullOrEmpty(_configFile))
                {
                    var dataConfigFile = System.Configuration.ConfigurationManager.AppSettings["DataConfigFile"];
                    if (string.IsNullOrEmpty(dataConfigFile))
                    {
                        _configFile = AppDomain.CurrentDomain.BaseDirectory + @"App_Config\data.cfg.xml";
                    }
                    else
                    {
                        _configFile = AppDomain.CurrentDomain.BaseDirectory + dataConfigFile;
                    }
                }

                return _configFile;
            }
            set
            {
                _configFile = value;
            }
        }
    }
}
